package com.xyz.timekeeper.database

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(database: SupportSQLiteDatabase) {
        // 创建新表
        database.execSQL(
            "CREATE TABLE time_records_new (" +
            "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
            "count INTEGER NOT NULL, " +
            "startTime TEXT NOT NULL, " +
            "displayStartTime TEXT NOT NULL, " +
            "endTime TEXT NOT NULL, " +
            "displayEndTime TEXT NOT NULL, " +
            "duration TEXT NOT NULL)"
        )
        
        // 复制旧数据
        database.execSQL(
            "INSERT INTO time_records_new (id, count, startTime, displayStartTime, endTime, displayEndTime, duration) " +
            "SELECT id, count, startTime, startTime, endTime, endTime, duration FROM time_records"
        )
        
        // 删除旧表
        database.execSQL("DROP TABLE time_records")
        
        // 重命名新表
        database.execSQL("ALTER TABLE time_records_new RENAME TO time_records")
    }
}

@Database(entities = [TimeRecord::class], version = 2)
abstract class TimeKeeperDatabase : RoomDatabase() {
    abstract fun timeRecordDao(): TimeRecordDao

    companion object {
        @Volatile
        private var INSTANCE: TimeKeeperDatabase? = null

        fun getDatabase(context: Context): TimeKeeperDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    TimeKeeperDatabase::class.java,
                    "timekeeper_database"
                )
                .addMigrations(MIGRATION_1_2)
                .fallbackToDestructiveMigration()
                .build()
                INSTANCE = instance
                instance
            }
        }
    }
}